#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <string>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

using std::cout;
using std::cin;
using std::cerr;
using std::endl;

int main(int argc, char* argv[])
{
    if (argc != 3)
    {
        cerr << "./TCPClient ip port\n";
        exit(-1);
    }

    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cerr << "socket error " << strerror(errno) << endl; 
        exit(1);
    }

    struct sockaddr_in server;
    bzero(&server, 0);
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    // 发起连接
    int flag = connect(sock, (sockaddr*)&server, sizeof server);
    if (flag < 0)
    {
        cerr << "connect error" << strerror(errno) << endl;
        exit(2);
    }

    // 连接成功
    std::string mes;
    char buffer[1024];
    while (true)
    {
        cout << "输入# ";
        std::getline(cin, mes);
        ssize_t flag = write(sock, mes.c_str(), mes.size());
        if (flag < 0)
        {
            cout << "写入失败！error write" << endl;
            break;
        }

        ssize_t n = recv(sock, buffer, 1024, 0);
        if (n > 0)
        {
            buffer[n] = '\0';
            cout << "服务器# " << buffer << endl;
        }
        else if (n == 0)
        {
            cout << "服务器已经断开连接!" << endl;
            close(sock);
            break;
        }
        else
        {
            // 读取错误
            cerr << "read error" << strerror(errno) << endl;
            close(sock);
            break;
        }
    }

}